<!-- 团购商品页面 -->
<template>
    <div>
        <div class="grid-content">
            <el-input v-model="data.spuName" class="m-2" placeholder="请输入商品名称" clearable />
            <el-input v-model="data.id" class="m-2" placeholder="请输入团购ID" clearable />
            <el-select v-model="data.status" placeholder="请选择广告状态" clearable class="m-2">
                <el-option v-for="item in groupStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button type="primary" :icon="Search" @click="init">查找</el-button>
            <el-button type="primary" :icon="Plus" @click="handlePageAdd">添加</el-button>
        </div>
        <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }">
            <el-table-column type="expand">
                <template #default="props">
                    <el-descriptions :column="1" border>
                        <el-descriptions-item label="类目ID" label-align="left" width="80">
                            {{ props.row.categoryId }}
                        </el-descriptions-item>
                        <el-descriptions-item align="left">
                            <el-table :data="props.row.groupShopSkuDTOList" border :cell-style="{ textAlign: 'center' }"
                                :header-cell-style="{ 'text-align': 'center' }">
                                <el-table-column label="SkuId" prop="skuId" />
                                <el-table-column label="规格标题" prop="title" width="120" />
                                <el-table-column label="团购价格(元)" prop="skuGroupShopPrice" />
                                <el-table-column label="库存">
                                    <template #default="props">{{ props.row.stock }}(件)</template>
                                </el-table-column>
                                <el-table-column label="原始价格(元)" prop="originalPrice" />
                                <el-table-column label="售卖价格(元)" prop="price" />
                                <el-table-column label="会员价格(元)" prop="vipPrice" />
                                <el-table-column label="国际条码" prop="barCode" />
                            </el-table>
                        </el-descriptions-item>
                    </el-descriptions>
                </template>
            </el-table-column>
            <el-table-column prop="id" label="团购ID" />
            <el-table-column prop="spuId" label="商品ID" width="100" />
            <el-table-column prop="title" label="商品名称" width="120" />
            <el-table-column label="商品主题">
                <template #default="props">
                    <el-popover trigger="hover" placement="right-start" width="300px">
                        <template #default>
                            <el-image :src="props.row.img" />
                        </template>
                        <template #reference>
                            <el-image :src="props.row.img" style="height: 70px;" />
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="未满策略">
                <template #default="props">
                    <el-tag :type="props.row.automaticRefund == 1 ? 'warning' : 'success'">
                        {{ props.row.automaticRefund ? '发货' : '退款' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="活动状态">
                <template #default="props">
                    <el-tag :type="props.row.status == 1 ? '' : 'danger'">
                        {{ props.row.status == 1 ? '活动' : '冻结' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="开始时间" width="175">
                <template #default="props">
                    {{ filDateTime(props.row.gmtStart) }}
                </template>
            </el-table-column>
            <el-table-column label="结束时间" width="175">
                <template #default="props">
                    {{ filDateTime(props.row.gmtEnd) }}
                </template>
            </el-table-column>
            <el-table-column prop="buyerNum" label="当前人数" />
            <el-table-column prop="minNum" label="目标人数" />
            <el-table-column label="操作" width="160">
                <template #default="scope">
                    <el-button type="primary" @click="handleEdit(scope.$index, scope.row)" v-if="scope.row.status != 1">
                        编辑
                    </el-button>
                    <el-button type="danger" @click="handleDelete(scope.$index, scope.row)"
                        v-if="scope.row.status != 1">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination v-bind="pagination" @page-change="handlePageChange" /><!--分页器-->
        <!-- 添加&编辑-抽屉弹框 -->
        <el-drawer v-model="isVisible" direction="ltr" :show-close="false" size="700px" class="drawer">
            <!-- 自定义抽屉头部 -->
            <template #header="{ titleId, titleClass }">
                <span :id="titleId" :class="titleClass">{{ drawerTitle }}</span>
                <el-button @click="isVisible = false">取消</el-button>
                <el-button type="primary" @click="determine(ruleFormRef)">
                    {{ drawerState == false ? '创建' : '编辑' }}
                </el-button>
            </template>
            <el-card class="form-card">
                <h4>商品属性(spu)</h4>
                <el-form :model="dataForm" label-position="left" label-width="100px" ref="ruleFormRef" :rules="rules">
                    <el-form-item prop="spuId" label="团购商品">
                        <el-cascader v-model="dataForm.spuId" :options="goodsTreeData" clearable
                            :props="{ emitPath: false, label: 'label', value: 'id', children: 'children' }"
                            @change="setGoods" />
                    </el-form-item>
                    <el-form-item label="团购时间">
                        <div class="picker">
                            <el-date-picker v-model="dataForm.gmtStart" type="datetime" placeholder="选择日期"
                                @change="getStartTime" />
                            <span>至</span>
                            <el-date-picker v-model="dataForm.gmtEnd" type="datetime" placeholder="选择日期"
                                @change="getEndTime" />
                        </div>
                    </el-form-item>
                    <el-form-item label="团购基础人数">
                        <el-input-number v-model="dataForm.minNum" :min="1" controls-position="right" />
                    </el-form-item>
                    <el-form-item label="活动结束时人数没有达到基础人数采取" label-width="150px">
                        <el-radio-group v-model="dataForm.automaticRefund">
                            <el-radio-button :label="0">不退款,我要发货</el-radio-button>
                            <el-radio-button :label="1">自动退款,我不发货</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </el-card>
            <el-card class="table-card">
                <template #header>
                    <div class="card-header">
                        <h4>商品类型(sku)</h4>
                        <el-popover placement="right" :width="400" trigger="click" v-model:visible="popoverFormVisible">
                            <template #reference>
                                <el-button ref="refBtnSetAllPrice" type="primary" plain
                                    :disabled="!dataForm.spuId ? true : false">批量定价</el-button>
                            </template>
                            <el-form label-position="left" label-width="100px">
                                <el-form-item label="团购价格">
                                    <el-input-number v-model.number="SkuUpdatePrice" :min="1"
                                        controls-position="right" />
                                    <span>元</span>
                                </el-form-item>
                                <el-form-item>
                                    <el-button @click="refBtnSetAllPrice.$el?.click?.()">取消</el-button>
                                    <el-button type="primary" @click="handleBatchSkuUpdate">确定</el-button>
                                </el-form-item>
                            </el-form>
                        </el-popover>
                    </div>
                </template>
                <el-table :data="dataForm.groupShopSkuDTOList" style="width: 100%" :cell-style="{ textAlign: 'center' }"
                    :header-cell-style="{ 'text-align': 'center' }">
                    <el-table-column prop="id" label="SkuId" width="70" />
                    <el-table-column prop="barCode" label="Sku条形码" width="100" />
                    <el-table-column prop="title" label="类型名" />
                    <el-table-column prop="stock" label="库存" />
                    <el-table-column prop="originalPrice" label="现价/元" />
                    <el-table-column prop="skuGroupShopPrice" label="团购价格/元" width="110" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button type="primary" @click="handleRenew(scope.$index, scope.row)">
                                更新
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-drawer>
        <!-- 商品类型(sku)表格更新弹框 -->
        <el-dialog v-model="dialogFormVisible" title="更新团购价格" width="600">
            <el-form :model="updateForm" label-position="left" label-width="100px">
                <el-form-item label="团购价格">
                    <el-input-number v-model.number="updateGroupPrice" :min="1" controls-position="right" />
                    <span>元</span>
                </el-form-item>
                <el-form-item label="现价">
                    {{ updateForm.price }}
                </el-form-item>
                <el-form-item label="sku类型名">
                    {{ updateForm.title }}
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="configRenew">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from "vue";
import { post, get } from '@/utils/http'//封装的axios请求方式
import { initObj } from '@/utils/index'
import { Search, Plus } from '@element-plus/icons-vue';//图标 
import type { FormInstance } from 'element-plus'//element类型数据
import { ElMessage, ElMessageBox } from 'element-plus'//提示信息
import { PaginationClass, GroupClass } from "#/index";//自定义表单分页数据类型
import { filDateTime } from "@/utils/time";//处理时间

const ruleFormRef = ref<FormInstance>()//操作form节点
const refBtnSetAllPrice = ref()//批量定价节点
const tableData = ref([])//表格数据
const goodsTreeData = ref([])//类目树形菜单数据
const pagination = ref(new PaginationClass())//分页数据
const isVisible = ref(false)//控制抽屉弹出隐藏
const popoverFormVisible = ref(false)//控制批量定价弹框隐藏
const dialogFormVisible = ref(false)//控制更新弹框显示隐藏
const groupStatusMap = reactive([//团购商品状态
    { value: 0, label: '冻结' },
    { value: 1, label: '活动' }
])
const rules = reactive({// 表单验证
    spuId: [{ required: true, message: '团购商品不能为空', trigger: 'blur' }]
})

let drawerTitle = computed(() => drawerState.value == false ? '创建团购商品' : '编辑团购商品')//判断弹框标题
let drawerState = ref(false)//控制抽屉弹框状态  
let dataForm = ref(new GroupClass())//抽屉绑定数据
let SkuUpdatePrice = ref()//批量定价的团购价格
let SkuUpdateIndex = ref()//商品类型表格下标
let updateGroupPrice = ref() //更新的团购价格
let data = reactive({ //请求传递的数据
    _gp: 'admin.groupshop',
    _mt: 'list',
    id: '', //团购商品的ID
    spuName: '', //团购商品的名称
    status: '', //团购商品的状态
    page: 1, //当前的页数
    limit: 10 //每页显示条数
})
let updateForm = ref({
    price: 0,//现价
    title: ''//sku类型名
})

onMounted(() => {
    init()
})

// 初始化数据
function init() {
    post(data).then((res) => {
        console.log(res);
        let { data: { items, total } } = res;
        tableData.value = items;//表格数据赋值
        pagination.value.total = total;//总页数赋值
    })
    GoodsTreeInfo()
}

// 初始化类目树形菜单数据
function GoodsTreeInfo() {
    post({ _gp: 'admin.product', _mt: 'getSpuBigTree' }).then((res) => {
        console.log(res);
        let { data } = res;
        goodsTreeData.value = data
    })
}

//初始化商品类型表格 获取商品类型
function productInfo(v: number) {
    if (dataForm.value.spuId != undefined) {
        post({ _gp: 'admin.product', _mt: 'detail', spuId: v }).then((res) => {
            console.log(res);
            let { skuList } = res.data;
            skuList.forEach((item: { skuId: number, id: number }) => {
                item.skuId = item.id
            });
            dataForm.value.groupShopSkuDTOList = skuList;
        })
    } else {
        ElMessage.warning('请选择团购商品')
    }

}

// 选择团购商品触发渲染商品类型表格
function setGoods(v: number) {
    productInfo(v)
}

//指定团购时间
function getStartTime(value: number) {
    dataForm.value.gmtStart = new Date(value).getTime()
}

//指定结束时间
function getEndTime(value: number) {
    dataForm.value.gmtEnd = new Date(value).getTime()
}

// 添加
function handlePageAdd() {
    isVisible.value = true;//显示抽屉弹框
    drawerState.value = false;//控制抽屉弹框为添加状态
    ruleFormRef.value?.resetFields();//重置表单初始值
    initObj(dataForm.value, { minNum: 1, mode: 1 })//重置商品属性表单
}

//编辑
function handleEdit(index: number, row: GroupClass) {
    isVisible.value = true;//显示抽屉弹框
    drawerState.value = true;//控制抽屉弹框为编辑状态
    ruleFormRef.value?.resetFields();//重置表单初始值
    Object.assign(dataForm.value, row);
    dataForm.value.groupShopSkuDTOList = JSON.parse(JSON.stringify(row.groupShopSkuDTOList));

}

// 抽屉弹框确定
function determine(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            post({
                _gp: 'admin.groupshop',
                _mt: drawerState.value == false ? 'create' : 'edit',
                ...dataForm.value,
                groupShopSkuList: JSON.stringify(dataForm.value.groupShopSkuDTOList)
            }).then((res) => {
                console.log(res);
                let { errmsg, errno } = res;
                200 == errno ? ElMessage.success(drawerState.value == false ? '添加成功!' : '编辑成功!') : ElMessage.error(errmsg);
                isVisible.value = false;//隐藏弹框
                init()
            })
        } else {
            return false
        }
    })
}

// 删除
function handleDelete(index: number, row: GroupClass) {
    ElMessageBox.confirm(
        '确定要删除吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    ).then(() => {
        get({ _gp: 'admin.groupshop', _mt: 'delete', id: row.id }).then((res) => {
            console.log(res);
            let { errmsg, errno } = res
            200 == errno ? ElMessage.success('删除已完成') : ElMessage.error(errmsg)
            init()
        })
    }).catch(() => {
        ElMessage.info('删除已取消')
    })
}

// 批量定价团购商品
function handleBatchSkuUpdate() {
    if (SkuUpdatePrice.value != undefined) {
        for (let i = 0; i < dataForm.value.groupShopSkuDTOList.length; i++) {
            if (SkuUpdatePrice.value > dataForm.value.groupShopSkuDTOList[i].price) {
                ElMessage.warning('团购价格不能大于现价')
                return
            }
        }
    } else {
        ElMessage.warning('团购价格不能为空')
    }
    dataForm.value.groupShopSkuDTOList.forEach((item) => {
        item.skuGroupShopPrice = SkuUpdatePrice.value
        return item
    })
    SkuUpdatePrice.value = undefined//重置批量团购商品价格
    popoverFormVisible.value = false//隐藏弹框
}

//更新
function handleRenew(index: number, row: any) {
    console.log(row);
    dialogFormVisible.value = true;//显示更新弹框
    SkuUpdateIndex.value = index;//商品类型下标赋值
    updateGroupPrice.value = undefined;//重置更新的团购价格
    updateForm.value = <{ price: number, title: string }>{ //绑定的更新表单数据赋值
        price: row.price,
        title: row.title
    }
}

//更新弹框确定事件
function configRenew() {
    dialogFormVisible.value = false;//隐藏更新弹框
    if (updateGroupPrice.value >= dataForm.value.groupShopSkuDTOList[SkuUpdateIndex.value].price) {
        ElMessage.warning('团购价格不能大于现价')
        return
    }
    //获取商品类型表格相应的下标的团购价格赋值
    dataForm.value.groupShopSkuDTOList[SkuUpdateIndex.value].skuGroupShopPrice = updateGroupPrice.value

}

// 分页组件里的数据赋值
function handlePageChange(v: PaginationClass) {
    data.page = v.page
    data.limit = v.limit
    init()
}
</script>
<style lang="less" scoped>
.grid-content {
    display: flex;
    margin-bottom: 20px;

    .m-2 {
        width: 200px;
        margin-right: 8px;
    }

    .el-button {
        margin: 0px 8px 0px 0px;
    }
}

.form-card {
    width: 100%;

    .el-form {
        width: 90%;
        margin: auto;

        .picker {
            display: flex;
            width: 100%;
            flex-wrap: nowrap;

            span {
                margin: 0px 10px;
            }
        }

    }
}

.table-card {
    width: 100%;

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}

.el-dialog {
    .el-form {
        width: 70%;
        margin: auto;
    }
}
</style>